﻿using UnityEngine;

namespace Game
{
    public class SceneObjectMoveComponent : ISceneComponent
    {
        public bool isMoving { get; private set; }
        
        private SceneMovableEntity _sceneObject;
        private Vector3 _moveSpeed;
        private Bounds _moveBounds;

        public SceneObjectMoveComponent()
        {
        }
        
        public void Dispose()
        {
        }

        public void Setup(SceneMovableEntity sceneObject, Vector3 moveSpeed)
        {
            _sceneObject = sceneObject;
            _moveSpeed = moveSpeed;
        }

        public void SetMoveBounds(Bounds bounds)
        {
            _moveBounds = bounds;
        }

        public void StartMove()
        {
            if (isMoving)
            {
                return;
            }

            isMoving = true;
        }

        public void StopMove()
        {
            if (!isMoving)
            {
                return;
            }

            isMoving = false;
        }
        
        public void Update(float deltaTime)
        {
            if (isMoving)
            {
                Vector3 moveDistance = deltaTime * _moveSpeed;
                if (_sceneObject.GetFlipY())
                {
                    moveDistance.x = -moveDistance.x;
                }

                if (_sceneObject.GetFlipX())
                {
                    moveDistance.y = -moveDistance.y;
                }

                Vector3 nextPosition = _sceneObject.localPosition + moveDistance;
                float halfWidth = _sceneObject.bounds.extents.x;
                if (nextPosition.x - halfWidth < _moveBounds.min.x)
                {
                    nextPosition.x = _moveBounds.min.x + halfWidth;
                }
                else if (nextPosition.x + halfWidth > _moveBounds.max.x)
                {
                    nextPosition.x = _moveBounds.max.x - halfWidth;
                }
                
                if (nextPosition.y < _moveBounds.min.y)
                {
                    nextPosition.y = _moveBounds.min.y;
                }
                else if (nextPosition.y > _moveBounds.max.y)
                {
                    nextPosition.y = _moveBounds.max.y;
                }
                _sceneObject.localPosition = nextPosition;
            }
        }
    }
}